import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { Routes } from "./routes";
import { local } from "@/utils/storage";
import { AccountApi } from "@/api/api";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: Routes.LOGIN,
    name: "Login",
    component: () => import("@/views/login/Login.vue"),
    meta: {
      title: "登录",
      activeMenuName: "Login",
    },
  },
  {
    path: Routes.NOT_FOUND,
    name: "404",
    component: () => import("@/views/exception/404/index.vue"),
  },
  {
    path: Routes.SERVER_ERROR,
    name: "500",
    component: () => import("@/views/exception/500/index.vue"),
  },
  {
    path: Routes.HOME,
    name: "Home",
    component: () => import("@/views/home/Home.vue"),
    meta: {
      title: "首页",
      activeMenuName: "Home",
    },
  },
  {
    path: Routes.KNOWLEDGE,
    name: "Knowledge",
    component: () => import("@/views/knowledge/index.vue"),
    meta: {
      title: "知识库管理",
      activeMenuName: "Knowledge",
    },
  },
  {
    path: '/knowledge',
    component: () => import("@/views/knowledge/index.vue"),
    children: [
      {
        path: ':id', // 动态路由参数
        name: 'KnowledgeDetail',
        component: () => import('@/views/knowledge/detail.vue')
      }
    ]
  }
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 导航守卫
// router.beforeEach(async (to, from, next) => {
//   // 判断是否访问的是登录页、注册页或错误页面，如果是，跳过请求，直接进入目标页面
//   if (to.path === "/login" || to.path === "/register" || to.path === "/404" || to.path === "/500") {
//     next();
//   } else {
//     const token = local.get("token");

//     // 如果目标页面是首页，直接跳转，不执行任何请求
//     if (to.path === "/home") {
//       next(); // 直接跳转到首页
//     } else {
//       const req = {
//         token: token,
//       };

//       // token 存在则放行
//       if (token) {
//         try {
//           // 向后端发送请求验证 token
//           await AccountApi.verifyToken(req);
//           next();
//         } catch (error) {
//           console.error("Token 验证失败:", error);
//           window.localStorage.removeItem("token");
//           next("/login");
//         }
//       } else {
//         next("/login");
//       }
//     }
//   }
// });

export default router;
